package dev.ece.core.cells.model.base;

import org.lwjgl.opengl.GL11;

import dev.ece.core.cells.model.AbstractUI;
import dev.ece.core.vertex.VAO;
import dev.ece.core.vertex.VBO;
import dev.ece.util.lib.Rectangle;
import dev.ece.util.lib.Vector2f;
import dev.ece.util.lib.Vector3f;
import dev.ece.util.tools.Camera;

/**
 * @author 潜行的青衣
 * @see
 */
public class SquareUI<T> extends AbstractUI<T> {

	private Vector3f[] vertice;
	
	private Vector2f[] uv;
	
	private VBO verticeVBO;
	
	private VBO uvVBO;
	
	private VAO vao;
	
	private float width;
	
	private float height;
	
	private Rectangle textureClipping;
	
	public SquareUI(float width, float height) {
		this(width, height, new Rectangle(0, 0, 1, 1));
	}
	
	public SquareUI(float width, float height, Rectangle textureClipping) {
		this.width = width;
		this.height = height;
		this.textureClipping = textureClipping;
		this.init();
		this.setup();
	}
	
	protected void init() {
		float hWidth = width / 2;
		float hHeight = height / 2;
		vertice = new Vector3f[4];
		vertice[0] = new Vector3f(- hWidth, hHeight, 0);
		vertice[1] = new Vector3f(- hWidth, - hHeight, 0);
		vertice[2] = new Vector3f(hWidth, hHeight, 0);
		vertice[3] = new Vector3f(hWidth, - hHeight, 0);
		uv = new Vector2f[4];
		uv[0] = new Vector2f(textureClipping.left, textureClipping.top);
		uv[1] = new Vector2f(textureClipping.left, textureClipping.bottom);
		uv[2] = new Vector2f(textureClipping.right, textureClipping.top);
		uv[3] = new Vector2f(textureClipping.right, textureClipping.bottom);
	}

	protected void setup() {
		verticeVBO = VBO.newInstance(vertice);
		uvVBO = VBO.newInstance(uv);
		VBO.unbind();
	}
	
	@Override
	public void destroy() {
		if(vao != null) {
			vao.destroy();
		}
		vao = null;
		vertice = null;
		uv = null;
	}

	@Override
	public void onInitialize() {
		vao = new VAO();
		vao.bind();
		vao.bindVertexArrayBuffer(verticeVBO, 3);
		vao.bindVertexArrayBuffer(uvVBO, 2);
		vao.finish();
		
		verticeVBO = null;
		uvVBO = null;
	}

	@Override
	public void onRender(Camera camera, T value) {
		vao.bind();
		GL11.glDrawArrays(GL11.GL_TRIANGLE_STRIP, 0, 4);
	}

	public Vector3f[] getVertice() {
		return vertice;
	}

	public Vector2f[] getUv() {
		return uv;
	}
	
	public float getWidth() {
		return width;
	}

	public float getHeight() {
		return height;
	}
	
}
